<template>
  <div class="chat-container">
    <!-- 左侧好友列表 -->
    <div class="friend-list">
      <div class="list-header">
        <h2>好友列表</h2>
        <div class="search-box">
          <i class="fas fa-search"></i>
          <input type="text" placeholder="搜索联系人" v-model="searchQuery">
        </div>
      </div>

      <div
          v-for="friend in filteredFriends"
          :key="friend.friendId"
          class="friend-item"
          :class="{ active: currentFriend?.friendId === friend.friendId }"
          @click="selectFriend(friend)"
      >
        <div class="friend-avatar">
          <img v-if="friend.avatar" :src="friend.avatar" alt="头像">
          <div v-else class="avatar-placeholder">{{ friend.nickname.charAt(0) }}</div>
        </div>
        <div class="friend-info">
          <div class="info-row">
            <h3>{{ friend.nickname }}</h3>
            <span class="status-badge" :class="friend.status.toLowerCase()">
              {{ getStatusText(friend.status) }}
            </span>
          </div>
          <div class="info-row">
            <span class="remark" v-if="friend.remark">{{ friend.remark }}</span>
            <span class="last-active">活跃: {{ formatDateTime(friend.lastActive) }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧聊天区域 -->
    <div class="chat-area">
      <div class="chat-header" v-if="currentFriend">
        <div class="user-info">
          <div class="user-avatar">
            <img v-if="currentFriend.avatar" :src="currentFriend.avatar" alt="头像">
            <div v-else class="avatar-placeholder">{{ currentFriend.nickname.charAt(0) }}</div>
          </div>
          <div>
            <h3>{{ currentFriend.nickname }}</h3>
            <p>{{ getStatusText(currentFriend.status) }} - 最后活跃: {{ formatTime(currentFriend.lastActive) }}</p>
          </div>
        </div>
        <div class="header-actions">
          <div class="remark-display" v-if="currentFriend.remark">
            备注：{{ currentFriend.remark }}
          </div>
        </div>
      </div>

      <div class="chat-messages" ref="messagesContainer">
        <div
            v-for="(message, index) in currentMessages"
            :key="index"
            class="message"
            :class="message.sender === 'user' ? 'sent' : 'received'"
        >
          <div class="avatar" v-if="message.sender !== 'user'">
            <img v-if="currentFriend.avatar" :src="currentFriend.avatar" alt="头像">
            <div v-else class="avatar-placeholder">{{ currentFriend.nickname.charAt(0) }}</div>
          </div>
          <div class="message-content">
            <div class="message-text">{{ message.content }}</div>
            <div class="timestamp">{{ formatTime(message.timestamp) }}</div>
          </div>
          <div class="avatar" v-if="message.sender === 'user'">
            <div class="avatar-placeholder">我</div>
          </div>
        </div>
      </div>

      <div class="chat-input">
        <div class="input-actions">
          <button @click="toggleEmojiPicker">
            <i class="fas fa-smile"></i>
          </button>
          <button>
            <i class="fas fa-paperclip"></i>
          </button>
        </div>
        <textarea
            v-model="inputMessage"
            @keydown.enter.exact.prevent="sendMessage"
            placeholder="输入消息..."
            rows="1"
            ref="textArea"
        ></textarea>
        <button @click="sendMessage" :disabled="!inputMessage.trim()">
          <i class="fas fa-paper-plane"></i>
        </button>
      </div>

      <div class="emoji-picker" v-if="showEmojiPicker">
        <span
            v-for="(emoji, index) in emojis"
            :key="index"
            @click="addEmoji(emoji)"
        >{{ emoji }}</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, computed, watch, nextTick, onMounted, onBeforeMount} from 'vue'
import {useChatSimpleStore} from "@/stores/chatSimpleStore.js";
import {useAuthStore} from "@/stores/authStore.js";

const chatSimpleStore = useChatSimpleStore()
const authStore = useAuthStore()

// 好友列表数据（根据API响应构建）
const friends = computed(() => chatSimpleStore.friendList)
const messages = computed(() => chatSimpleStore.privateChatMessages)
// 当前选中的好友
const currentFriend = ref(null)

// 当前聊天的消息记录
const currentMessages = computed(() => {
  if (!currentFriend.value) return []
  return messages.value[currentFriend.value.friendId] || []
})

// 搜索功能
const searchQuery = ref('')
const filteredFriends = computed(() => {
  if (!searchQuery.value) return friends.value
  const query = searchQuery.value.toLowerCase()
  return friends.value.filter(friend =>
      friend.nickname.toLowerCase().includes(query) ||
      (friend.remark && friend.remark.toLowerCase().includes(query))
  )
})

// 状态文本转换
const getStatusText = (status) => {
  const statusMap = {
    'ONLINE': '在线',
    'OFFLINE': '离线',
    'BUSY': '忙碌',
    'AWAY': '离开'
  }
  return statusMap[status] || status
}

// 选择好友
const selectFriend = (friend) => {
  currentFriend.value = friend
}

// 发送消息
const inputMessage = ref('')
const sendMessage = () => {
  if (!inputMessage.value.trim() || !currentFriend.value) return

  const newMessage = {
    from: authStore.user.id,
    to: currentFriend.value.friendId,
    content: inputMessage.value,
    type: 'TEXT',
    timestamp: new Date().toISOString(),
    messageId: Date.now().toString(),
    sender:'user'
  }
  // 添加到当前聊天记录
  messages.value[currentFriend.value.friendId] = messages.value[currentFriend.value.friendId] || []
  messages.value[currentFriend.value.friendId].push(newMessage)

  inputMessage.value = ''
  chatSimpleStore.sendToUser(newMessage.content,currentFriend.value.friendId)

}

// 表情选择功能
const showEmojiPicker = ref(false)
const emojis = ['😀', '😂', '😍', '🤔', '👍', '👋', '🎉', '❤️', '🙏']
const addEmoji = (emoji) => {
  inputMessage.value += emoji
  showEmojiPicker.value = false
}
const toggleEmojiPicker = () => {
  showEmojiPicker.value = !showEmojiPicker.value
}

// 日期时间格式化
const formatTime = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'})
}

const formatDateTime = (dateString) => {
  const date = new Date(dateString)
  const today = new Date()
  const yesterday = new Date(today)
  yesterday.setDate(yesterday.getDate() - 1)

  if (date.toDateString() === today.toDateString()) {
    return date.toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'})
  } else if (date.toDateString() === yesterday.toDateString()) {
    return '昨天 ' + date.toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'})
  } else {
    return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'})
  }
}

// 自动滚动到底部
const messagesContainer = ref(null)
watch(currentMessages, async () => {
  await nextTick()
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}, {deep: true})

// 自动调整输入框高度
const textArea = ref(null)
watch(inputMessage, () => {
  if (textArea.value) {
    textArea.value.style.height = 'auto'
    textArea.value.style.height = Math.min(textArea.value.scrollHeight, 150) + 'px'
  }
})

onBeforeMount(() => {
   chatSimpleStore.connect();
})

// 初始化：默认选中第一个好友
onMounted(() => {
})
</script>

<style scoped>
.chat-container {
  display: flex;
  width: 100%;
  max-width: 1200px;
  height: 90vh;
  margin: 0 auto;
  background: linear-gradient(135deg, #1a2a6c, #2b5876);
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

/* 左侧好友列表样式 */
.friend-list {
  width: 35%;
  min-width: 300px;
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(10px);
  border-right: 1px solid rgba(255, 255, 255, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.list-header {
  padding: 20px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.list-header h2 {
  color: white;
  margin-bottom: 15px;
  font-weight: 600;
  font-size: 1.8rem;
}

.search-box {
  position: relative;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 20px;
  padding: 5px 15px;
}

.search-box .fa-search {
  color: #a0d2eb;
  margin-right: 10px;
}

.search-box input {
  width: 100%;
  background: transparent;
  border: none;
  color: white;
  font-size: 1rem;
  padding: 8px;
  outline: none;
}

.search-box input::placeholder {
  color: rgba(255, 255, 255, 0.5);
}

.friend-item {
  display: flex;
  padding: 15px 20px;
  cursor: pointer;
  transition: background 0.3s;
  border-bottom: 1px solid rgba(255, 255, 255, 0.05);
}

.friend-item:hover {
  background: rgba(255, 255, 255, 0.08);
}

.friend-item.active {
  background: rgba(255, 255, 255, 0.15);
}

.friend-avatar {
  margin-right: 15px;
}

.friend-avatar img, .avatar-placeholder {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(45deg, #ff9a9e, #fad0c4);
  color: white;
  font-weight: bold;
  font-size: 20px;
}

.friend-info {
  flex: 1;
  overflow: hidden;
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.friend-info h3 {
  color: white;
  font-size: 1.1rem;
  margin-bottom: 5px;
  font-weight: 600;
}

.status-badge {
  font-size: 0.8rem;
  padding: 2px 8px;
  border-radius: 10px;
}

.status-badge.online {
  background: rgba(46, 204, 113, 0.3);
  color: #2ecc71;
}

.status-badge.offline {
  background: rgba(149, 165, 166, 0.3);
  color: #95a5a6;
}

.status-badge.busy {
  background: rgba(231, 76, 60, 0.3);
  color: #e74c3c;
}

.status-badge.away {
  background: rgba(241, 196, 15, 0.3);
  color: #f1c40f;
}

.remark {
  color: #a0d2eb;
  font-size: 0.85rem;
  font-style: italic;
}

.last-active {
  color: rgba(255, 255, 255, 0.6);
  font-size: 0.8rem;
  margin-left: 10px;
}

.api-response {
  background: rgba(0, 0, 0, 0.2);
  color: #50fa7b;
  padding: 15px;
  margin: 15px;
  border-radius: 8px;
  font-size: 0.85rem;
  overflow: auto;
  max-height: 200px;
  display: none;
}

.api-response pre {
  white-space: pre-wrap;
}

/* 右侧聊天区域样式 */
.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: rgba(0, 0, 0, 0.1);
  position: relative;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 25px;
  background: rgba(0, 0, 0, 0.2);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.user-info {
  display: flex;
  align-items: center;
}

.user-avatar {
  margin-right: 15px;
}

.user-avatar img, .user-avatar .avatar-placeholder {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  object-fit: cover;
}

.user-info h3 {
  color: white;
  font-size: 1.2rem;
  margin-bottom: 5px;
}

.user-info p {
  color: #a0d2eb;
  font-size: 0.9rem;
}

.header-actions {
  display: flex;
  align-items: center;
}

.remark-display {
  background: rgba(255, 255, 255, 0.1);
  color: #a0d2eb;
  padding: 5px 12px;
  border-radius: 15px;
  font-size: 0.9rem;
  margin-right: 15px;
}

.header-actions button {
  background: rgba(255, 255, 255, 0.1);
  color: #a0d2eb;
  border: none;
  padding: 8px 15px;
  border-radius: 20px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: all 0.3s;
}

.header-actions button:hover {
  background: rgba(78, 110, 245, 0.5);
  color: white;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 25px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  background: url('https://www.transparenttextures.com/patterns/cubes.png') rgba(0, 0, 0, 0.1);
  background-blend-mode: overlay;
}

.message {
  display: flex;
  gap: 12px;
  max-width: 80%;
  animation: fadeIn 0.3s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.message.received {
  align-self: flex-start;
}

.message.sent {
  align-self: flex-end;
  flex-direction: row;
}

.avatar img, .avatar .avatar-placeholder {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.message-content {
  max-width: calc(100% - 52px);
}

.message-text {
  padding: 12px 18px;
  border-radius: 18px;
  font-size: 1rem;
  line-height: 1.4;
}

.message.received .message-text {
  background: rgba(255, 255, 255, 0.15);
  color: white;
  border-bottom-left-radius: 5px;
}

.message.sent .message-text {
  background: rgba(78, 110, 245, 0.9);
  color: white;
  border-bottom-right-radius: 5px;
}

.timestamp {
  font-size: 0.75rem;
  color: rgba(255, 255, 255, 0.6);
  padding: 5px 8px 0;
}

.chat-input {
  display: flex;
  padding: 15px 20px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  align-items: flex-end;
  background: rgba(0, 0, 0, 0.15);
}

.input-actions {
  display: flex;
  margin-right: 10px;
}

.input-actions button {
  background: transparent;
  border: none;
  color: #a0d2eb;
  font-size: 1.2rem;
  margin-right: 12px;
  cursor: pointer;
  transition: color 0.3s;
}

.input-actions button:hover {
  color: white;
}

.chat-input textarea {
  flex: 1;
  min-height: 46px;
  max-height: 150px;
  padding: 12px 18px;
  border-radius: 25px;
  border: none;
  background: rgba(0, 0, 0, 0.25);
  color: white;
  font-size: 1rem;
  resize: none;
  outline: none;
}

.chat-input textarea::placeholder {
  color: rgba(255, 255, 255, 0.5);
}

.chat-input button {
  width: 46px;
  height: 46px;
  border-radius: 50%;
  border: none;
  background: rgba(78, 110, 245, 0.9);
  color: white;
  margin-left: 12px;
  cursor: pointer;
  font-size: 1.2rem;
  transition: background 0.3s;
}

.chat-input button:disabled {
  background: rgba(255, 255, 255, 0.2);
  cursor: not-allowed;
}

.emoji-picker {
  position: absolute;
  bottom: 80px;
  right: 20px;
  background: rgba(0, 0, 0, 0.8);
  border-radius: 12px;
  padding: 10px;
  display: flex;
  flex-wrap: wrap;
  width: 250px;
  max-height: 200px;
  overflow-y: auto;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
  z-index: 100;
}

.emoji-picker span {
  font-size: 1.8rem;
  cursor: pointer;
  padding: 5px;
  transition: transform 0.2s;
}

.emoji-picker span:hover {
  transform: scale(1.2);
}
</style>